package com.dehui.traders.ui.login;

import android.app.ProgressDialog;
import android.content.Context;
import android.databinding.ObservableField;
import android.text.TextUtils;
import android.util.Log;

import com.dehui.traders.R;
import com.dehui.traders.bean.BaseListResponse;
import com.dehui.traders.bean.BaseResponse;
import com.dehui.traders.bean.UserInfo;
import com.dehui.traders.config.Preferences;
import com.dehui.traders.service.CallListener;
import com.dehui.traders.service.NetImpl;
import com.dehui.traders.ui.register.RegisterActivity;
import com.dehui.traders.utils.DialogHelp;
import com.dehui.traders.utils.MD5;
import com.google.gson.Gson;
import com.mob.MobSDK;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.utils.ToastUtils;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by hqq on 18.4.4.
 */

public class LoginViewModel extends BaseViewModel{

    private LoginActivity activity;

    public LoginViewModel(Context context) {
        super(context);
    }

    public ObservableField<String> phone = new ObservableField<>("");

    public ObservableField<String> loginName = new ObservableField<>("你好，游客");

    public ObservableField<String> pwd = new ObservableField<>("");

    public BindingCommand loginOnClickCommand = new BindingCommand(()->{
        login();
    });

    public BindingCommand titleRegisterCommand = new BindingCommand(()->{
        RegisterActivity.start(context);
    });

    public BindingCommand weichatCommand = new BindingCommand(()->{
        wxLogin();
    });

    private void wxLogin() {
        MobSDK.init(context);
        Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
        wechat.removeAccount(true);
        wechat.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                // TODO Auto-generated method stub
                Log.e("Hqq","complete" + arg1);
                PlatformDb db = arg0.getDb();
                toWxLogin(db.getToken(),db.getUserId(),db.getUserIcon(),db.getUserName());
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
            }
        });
        wechat.showUser(null);

    }

    private void toWxLogin(String token, String userId, String userIcon, String userName) {
        String registrationID = JPushInterface.getRegistrationID(context);
        Call<BaseListResponse<UserInfo>> call = NetImpl.wxLogin(token, userId, userIcon, userName,registrationID);
        call.enqueue(new CallListener<BaseListResponse<UserInfo>>() {
            @Override
            public void _onResponse(Response<BaseListResponse<UserInfo>> response) {
                BaseListResponse<UserInfo> body = response.body();
                if (body.status == 200){
                    UserInfo userInfo = body.result.get(0);
                    Preferences.saveToken(userInfo.getToken());
                    Preferences.saveUserId(userInfo.getUserId());
                    Preferences.saveUserNickName(userInfo.getNickname());
                    Preferences.saveImageUrl(userInfo.getHeadimgurl());
                    ToastUtils.showShort("登录成功");
                    activity.finish();
                }else {
                    ToastUtils.showShort(R.string.login_error);
                }
            }

            @Override
            public void _onFailure() {
                ToastUtils.showShort(R.string.login_error);
            }
        });
    }

    private ProgressDialog loadingDialog;

    private void login() {
        if (TextUtils.isEmpty(phone.get())){
            ToastUtils.showShort(R.string.please_input_phone);
        }else if(TextUtils.isEmpty(pwd.get())){
            ToastUtils.showShort(R.string.please_input_password);
        }else {
            toLogin();
        }
    }

    private void toLogin() {
        loadingDialog = DialogHelp.getLoadingDialog(context);
        loadingDialog.show();
        String registrationID = JPushInterface.getRegistrationID(context);
        Call<BaseResponse<Object>> call = NetImpl.login(phone.get(), MD5.md5(pwd.get()).toLowerCase(),registrationID);
        call.enqueue(new CallListener<BaseResponse<Object>>() {
            @Override
            public void _onResponse(Response<BaseResponse<Object>> response) {
                loadingDialog.dismiss();
                BaseResponse<Object> loginTokenBaseResponse = response.body();
                int status = loginTokenBaseResponse.status;
                if (status == 200){
                    ToastUtils.showShort(R.string.login_success);
                    Object obj = loginTokenBaseResponse.result;
                    String s = new Gson().toJson(obj);
                    UserInfo userInfo = new Gson().fromJson(s, UserInfo.class);
                    Preferences.saveToken(userInfo.getToken());
                    Preferences.saveUserId(userInfo.getUserId());
                    Preferences.saveUserNickName(userInfo.getNickname());
                    Preferences.saveImageUrl(userInfo.getHeadimgurl());
                    Preferences.savePhone(phone.get());
                    ToastUtils.showShort("登录成功");

                    activity.finish();
                }else{
                    ToastUtils.showShort(R.string.login_error);
                }

            }

            @Override
            public void _onFailure() {
                loadingDialog.dismiss();
            }
        });
    }


    @Override
    public void onCreate() {
        super.onCreate();
    }

    public void setThis(LoginActivity activity) {
        this.activity = activity;
    }
}
